package com.wangfugui.mybatisplus.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.SearchTerm;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

public class WeChatWorkEmailAttachmentDownloader {

    public static void main(String[] args) {
        // 企业微信邮箱配置
        String host = "imap.exmail.qq.com"; // IMAP服务器
        String username = "shenghong@qidianqiuxue.com"; // 邮箱地址
        String password = "Qidian842"; // 密码或授权码

        // 下载附件的保存目录
        String saveDirectory = "/Users/zhaolele/Documents/mail";

        try {
            downloadAttachments(host, username, password, saveDirectory);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void downloadAttachments(String host, String username,
                                         String password, String saveDirectory) throws Exception {
        // 设置邮件服务器属性
        Properties properties = new Properties();
        properties.put("mail.store.protocol", "imap");
        properties.put("mail.imap.host", host);
        properties.put("mail.imap.port", "993");
        properties.put("mail.imap.ssl.enable", "true");
        properties.put("mail.imap.auth", "true");

        // 创建会话
        Session session = Session.getDefaultInstance(properties, null);
        Store store = null;
        Folder inbox = null;

        try {
            // 连接到邮件服务器
            store = session.getStore("imap");
            store.connect(host, username, password);

            // 打开收件箱
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            //创建日期搜索条件
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            Date today = calendar.getTime();
            SearchTerm searchTerm = new ReceivedDateTerm(ComparisonTerm.GE, today);
            // 获取邮件
            Message[] messages = inbox.search(searchTerm);
//            Message[] messages = inbox.getMessages();
            System.out.println("Total messages: " + messages.length);

            for (int i = 0; i < messages.length; i++) {
                Message message = messages[i];
                String subject = message.getSubject();
                Address[] from = message.getFrom();
                if (from ==null || from.length == 0){
                    continue;
                }
                if (!(from[0] instanceof InternetAddress)){
                    continue;
                }
                InternetAddress internetAddress = (InternetAddress) from[0];
                String address = internetAddress.getAddress();
                if (!address.equals("no_reply@notification.futuhk.com")){
                    continue;
                }

                System.out.println("Processing message: " + subject);
                // 检查邮件是否有附件
                if (message.getContent() instanceof Multipart) {
                    Multipart multipart = (Multipart) message.getContent();

                    for (int j = 0; j < multipart.getCount(); j++) {
                        BodyPart bodyPart = multipart.getBodyPart(j);

                        if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                            // 处理附件
                            String fileName = bodyPart.getFileName();
                            System.out.println("Found attachment: " + fileName);

                            // 保存附件
                            InputStream is = bodyPart.getInputStream();
                            File f = new File(saveDirectory + File.separator + fileName);
                            FileOutputStream fos = new FileOutputStream(f);

                            byte[] buf = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = is.read(buf)) != -1) {
                                fos.write(buf, 0, bytesRead);
                            }

                            fos.close();
                            is.close();
                            System.out.println("Attachment saved to: " + f.getAbsolutePath());
                        }
                    }
                }
            }
        } finally {
            // 关闭连接
            if (inbox != null) {
                inbox.close(false);
            }
            if (store != null) {
                store.close();
            }
        }
    }
}
